#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 00:47:08 2020

@author: ua17
"""
# columns = ['loadingOrder','carrierName','timestamp','lon',
#                   'lat','vesselMMSI','speed','direction','vesselNextport',
#                   'vesselNextportETA','vesselStatus','vesselDatasource','TRANSPORT_TRACE']
columns_orginal = ["loadingOrder","timestamp",'lon','lat','speed','direction','carrierName',
           'vesselMMSI','onboardDate','TRANSPORT_TRACE',
           'start_LONGITUDE','start_LATITUDE','end_LONGITUDE','end_LATITUDE']
columns = ["loadingOrder",'carrierName',"timestamp",'lon','lat','speed','direction',
           'vesselMMSI','onboardDate','TRANSPORT_TRACE',
           'start_LONGITUDE','start_LATITUDE','end_LONGITUDE','end_LATITUDE']


import pandas as pd

from utils import *     


ANCHOR_MAX = 3

def merge_block(arr):
    data = pd.read_csv(arr, header=None)
    data.columns = columns_orginal
    print(len(data),end="\t")
    for fl_col in ['lon', 'lat', 'speed']:
        data[fl_col] = data[fl_col].astype(float)
    
    for ts_col in ['timestamp']:
        data[ts_col] = pd.to_datetime(data[ts_col], infer_datetime_format=True)
    
    last_lon, last_lat, last_ts = 0, 0, 0
    lines = []
    data = data[columns] #
    for row in data.itertuples():
        lon, lat, ts = row[4], row[5], row[3]
        distance, seconds, speed = compute_diff(lon, lat, ts, last_lon, last_lat, last_ts)
        anchor = 1 if speed < ANCHOR_MAX else 0
        
        if distance >=0 :
            last_lon, last_lat, last_ts = lon, lat, ts
            bag = [anchor, speed, seconds, distance]
            bag.extend(row[1:])
            lines.append(bag)

    print("->", len(lines), end="\t")
    return lines


LOLA_RANGE = 5
columns2 = ['anchor','speed1', 'seconds', 'distance',"loadingOrder",
            'carrierName',"timestamp",'lon','lat','speed','direction',
           'vesselMMSI','onboardDate','TRANSPORT_TRACE',
           'start_LONGITUDE','start_LATITUDE','end_LONGITUDE','end_LATITUDE']

columns3 = ["remain_seconds", "complete_ratio", "relative_direction", "relative_distance", "relative_x", "relative_y",
            "abs_x", "abs_y", "block_start", "block_current","block_end", "sum_distance","dst_anchor"
            ] + columns2


def lola_compute(lola_current, lola_next, lola_dst):
    small_triangle = get_degrees(lola_current, lola_next, lola_dst) if lola_dst != lola_next else (0, 90, 90)
    relative_direction = cos(radians(small_triangle[0]))
    relative_distance = get_distance(*lola_current, *lola_dst)
    relative_x, relative_y = shadow(*lola_current, *lola_dst)
    abs_x, abs_y = shadow(*lola_current, *lola_next)
    return relative_direction, relative_distance, relative_x, relative_y,abs_x, abs_y


def process_block(lines):
    result_lines = []
    start, end = lines[0], lines[-1][:]
    end[7], end[8] = end[16], end[17] #mork
    lola_start,lola_end = start[7:9], end[7:9]
    seconds_total = sum([x[2] for x in lines])
    block_start = "{}_{}".format(round(lola_start[0])//LOLA_RANGE, round(lola_start[1])//LOLA_RANGE)
    block_end = "{}_{}".format(round(lola_end[0])//LOLA_RANGE, round(lola_end[1])//LOLA_RANGE)
    sum_seconds, sum_distance, legals = 0, 0, 0
    for i in range(1, len(lines)-1):
        current, next = lines[i], lines[i+1]
        block_current = "{}_{}".format(round(current[7])//LOLA_RANGE, round(current[8])//LOLA_RANGE)
        try:
            relative_direction, relative_distance, relative_x, relative_y,abs_x, abs_y \
                = lola_compute(current[7:9], next[7:9], lola_end)
            legals += 1
        except Exception:
            print("[{}]".format(legals), end=",")
            continue
        sum_seconds += current[2]
        sum_distance += current[3]
        remain_seconds = seconds_total - sum_seconds
        complete_ratio = sum_seconds / seconds_total
        result_lines.append([remain_seconds, complete_ratio, relative_direction, relative_distance, relative_x, relative_y,
                             abs_x, abs_y, block_start, block_current,block_end, sum_distance, 1
                             ] + current)

    print(" > {} processed ".format(legals), end=" ")

    return result_lines
